<?php
/**
 * 店铺管理类
 */
namespace App\Controller\Member;
use Common\Controller\App\CommonController;
use Common\Model\MemberModel;
use Common\Model\MicroShopBonusDetailModel;
use Common\Model\MicroShopBonusGetRecordsModel;
use Common\Model\MicroShopModel;
use Common\Model\MicroShopSalesFlowModel;
use Common\Model\NewsDataModel;
use Common\Model\NewsModel;
use Common\Model\OrderModel;
use Common\Model\OrderProductModel;
use Common\Model\TarentoBankAccountModel;
use Common\Model\TarentoCashFlowModel;
use Common\Model\TarentoModel;
use Common\Model\TarentoWithdrawApplyModel;
use Think\Helper;

class ShopController extends CommonController{
    /**
     * 店铺管理首页
     */
    public function index(){
        $member_id = session('member_id');
        $news_list = $this->news_list();
        $shopModel = new MicroShopModel();
        $shop_info = $shopModel->alias('s')->join("left join haiou_tarento as t on s.member_id=t.member_id")->where("s.member_id=$member_id and s.status>0")->field("s.logo,s.name,s.level,t.invite_code,t.account")->find();
        $orderModel = new OrderModel();
        $order_count = $orderModel->where("ms_id=$member_id and master_order_id='' and status !=-9")->count();
        $total_sales_price = 0;
        //获取累计销售额 micro_shop_sales_flow
        $mssf_model = new MicroShopSalesFlowModel();
        $list = $mssf_model->where("member_id=$member_id")->field("self_sales,group_sales")->select();
        foreach($list as $v){
            $total_sales_price += ($v['self_sales'] + $v['group_sales']);
        }
        //获取粉丝人数
        $model = new TarentoModel();
        $fens_num = $model->where("direct_rec_mid=$member_id")->count();
        $this->ajaxReturn(['code'=>200,'fens_num'=>$fens_num,'total_sales_price'=>$total_sales_price,'news_list'=>$news_list,'shop_info'=>$shop_info,'order_count'=>$order_count]);
    }

    /**
     * 获取新闻列表
     */
    public function news_list($page=1,$limit=20){
        $newModel = new NewsModel();
        $num = ($page-1)*$limit;
        $list = $newModel->getlist(28,$num,$limit);
        return $list;
    }

    /**
     * 我的收益（首页）
     */
    public function profit_index(){
        $member_id = session('member_id');
        $model = new TarentoModel();
        //用户余额
        $user_account = $model->where("member_id=$member_id")->field("account")->find();
        //累计收益
        $model = new MicroShopBonusDetailModel();
        $total_price = $model->where("member_id=$member_id and status!=9")->field("sum(price) as price")->find();
        //待收益
        $stay_price = $model->where("member_id=$member_id and status='-1'")->field("sum(price) as price")->find();
        //判断是否有提现账号
        $model = new TarentoBankAccountModel();
        $info = $model->where("member_id=$member_id")->find();
        $is_account = 0;
        if($info){
            $is_account = 1;
        }
        //获取已提现金额   Withdrawals
        $model = new TarentoWithdrawApplyModel();
        $withdrawals = $model->where("member_id=$member_id and status=9")->field("sum(apply_money) as money")->find();
        if(empty($withdrawals['money'])){
            $withdrawals['money'] = 0;
        }
        $this->ajaxReturn(['code'=>200,'user_account'=>$user_account['account'],'total_price'=>$total_price['price'],'stay_price'=>$stay_price['price'],'is_account'=>$is_account,'withdrawals'=>$withdrawals['money']]);
    }
    /**
     *待收益列表
     */
    public function stay_list(){
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $num = ($page-1)*$limit;
        $member_id = session('member_id');
        $model = new MicroShopBonusDetailModel();
        $res = $model->getEarnOrderIds($member_id,$num,$limit);
        if (!empty($res['watitingEarnOrderIds'])) {//存在未收益订单
            //获取订单信息
            $orderIdWithBonusId = array_flip($res['watitingEarnOrderIds']);
            $orderModel = new OrderModel();
            $orders = $orderModel->getWaitingEarnOrdersByOrderIds($res['watitingEarnOrderIds']);

            foreach ($orders as $k => $v) {
                //获取订单支付金额
                $Helper = new Helper();
                $orders[$k]['pay_price'] = $Helper->getPayPrice($v)<0?0:$Helper->getPayPrice($v);
                //获取与当前店铺红包信息
                $model = new MicroShopBonusDetailModel();
                $orders[$k]['bonusInfo'] = $model->getInfoById($orderIdWithBonusId[$v['order_id']]);
            }
        }
        //$result = ['orderList' => $orders];
        $this->ajaxReturn(['code'=>200,'list'=>$orders]);

    }

    /**
     * 带收益详情
     */
    public function saty_view(){
        $order_id = I('post.order_id');
        $orderModel = new OrderModel();
        $order = $orderModel->getWaitingEarnOrdersByOrderId($order_id);

        //获取订单支付金额
        $Helper = new Helper();
        $order['pay_price'] = $Helper->getPayPrice($order)<0?0:$Helper->getPayPrice($order);
        //获取与当前店铺红包信息
        $model = new MicroShopBonusDetailModel();
        $order['bonusInfo'] = $model->getInfoById($order_id);
        $this->ajaxReturn(['code'=>200,'list'=>$order]);
    }

    /**
     * 提现列表
     */
    public function w_list(){
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $num = ($page-1)*$limit;
        $member_id = session('member_id');
        $model = new TarentoWithdrawApplyModel();
        $list = $model->where("member_id=$member_id")->field("apply_money,apply_time,status")->limit($num,$limit)->select();
        $this->ajaxReturn(['code'=>200,'list'=>$list]);
    }
    /**
     * 提现账户列表
     */
    public function cash_withdrawal_account_list(){
        $member_id = session('member_id');
        $model = new TarentoBankAccountModel();
        $list = $model->where("member_id=$member_id and status=1")->order("is_default desc")->select();
        $list_type = $model->getAccountsType();
        foreach($list as $k=>$v){
            foreach($list_type as $y){
                if($v['account_type'] == $y['code']){
                    $list[$k]['code'] = $y['name'];
                }
            }
        }
        $this->ajaxReturn(['code'=>200,'list'=>$list]);
    }
    /**
     * 提现账户添加
     */
    public function cash_withdrawal_account_add(){
        $member_id = session('member_id');
        $account_name = I('post.account_name');
        $account_number = I('post.account_number');
        $account_type  = I('post.account_type');
        $account_bank_addr  = I('post.account_bank_addr');
        $is_default  = I('post.is_default');
        $model = new TarentoBankAccountModel();

        $id  = I('post.id');
        if(empty($account_name)){
            $this->ajaxReturn(['code'=>300,'msg'=>'请输入正确的姓名']);
        }
        if(empty($account_number)){
            $this->ajaxReturn(['code'=>300,'msg'=>'请输入正确的提现账号']);
        }
        $data['account_name'] = $account_name;
        $data['account_number'] = $account_number;
        $data['account_type'] = $account_type;
        $data['account_bank_addr'] = $account_bank_addr;
        if($id){
            $data['update_time'] = date('Y-m-d H:i:s',time());
            if($is_default == 1){
                $data['is_default'] = 1;
                $model->where("member_id=$member_id")->save(['is_default'=>0]);
            }
            $result = $model->where("member_id=$member_id and id=$id")->save($data);
        }else{
            $info = $model->where("account_number='$account_number' and member_id=$member_id and account_type=$account_type")->find();
            if($info){
                $this->ajaxReturn(['code'=>300,'msg'=>'此账号已存在']);
            }
            $data['is_default'] = 1;
            $data['member_id'] = $member_id;
            $data['update_time'] = date('Y-m-d H:i:s',time());
            $data['create_time'] = date('Y-m-d H:i:s',time());
            $result = $model->add($data);
        }
        if($result){
            $this->ajaxReturn(['code'=>200,'msg'=>'提现账户操作成功']);
        }else{
            $this->ajaxReturn(['code'=>200,'msg'=>'提现账户操作失败']);
        }
    }

    /**
     * 提现账户添加，修改
     */
    public function cash_withdrawal_account_edit(){
        $member_id = session('member_id');
        $id = I('post.id');
        if($id){
            $model = new TarentoBankAccountModel();
            $info = $model->where("member_id=$member_id and id=$id")->find();
        }
        if(empty($info)){
            $info = [];
        }
        $model = new TarentoBankAccountModel();
        $list = $model->getAccountsType();
        $this->ajaxReturn(['code'=>200,'info'=>$info,'list'=>$list]);
    }

    /**
     * 提现账户删除
     */
    public function cash_withdrawal_account_delete(){
        $member_id = session('member_id');
        $id = I('post.id');
        $model = new TarentoBankAccountModel();
        if(empty($id)){
            $this->ajaxReturn(['code'=>300,'msg'=>'您好，你好删除的提现账号编号错误']);
        }
        $result = $model->where("member_id=$member_id and id=$id")->delete();
        if($result){
            $this->ajaxReturn(['code'=>200,'msg'=>'提现账户删除成功']);
        }else{
            $this->ajaxReturn(['code'=>200,'msg'=>'提现账户删除失败']);
        }
    }


    /**
     * 提现金额
     */
    public function withdrawal_price(){
        $member_id = session('member_id');
        $model = new TarentoModel();
        $info = $model->where("member_id=$member_id")->field("account")->find();
        $this->ajaxReturn(['code'=>200,'price'=>$info['account']]);
    }

    /**
     * 快讯列表
     */
    public function k_lists(){
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $list = $this->news_list($page,$limit);
        $this->ajaxReturn(['code'=>200,'list'=>$list]);
    }

    /**
     * 快讯详情
     */
    public function k_info(){
        $nid = I('post.nid');
        $model = new NewsDataModel();
        $info = $model->where("nid=$nid")->find();
        $this->ajaxReturn(['code'=>200,'info'=>$info]);
    }

    /**
     * 申请提现
     */
    public function withdrawal(){
        $member_id = session('member_id');
        $model = new MemberModel();
        $m_info = $model->alias('a')->join("left join haiou_tarento as b on a.userid=b.member_id")->where("userid=$member_id")->field("a.mobile,b.account")->find();
        if(empty($m_info['mobile'])){
            $this->ajaxReturn(['code'=>300,'msg'=>'您好，你还未绑定手机号，请先绑定手机号']);
        }
        $model = new TarentoBankAccountModel();
        $info = $model->where("member_id=$member_id and is_default=1")->field("id,account_name,account_number,account_type")->find();
        $info['mobile'] = $m_info['mobile'];
        $info['account'] = $m_info['account'];
        $res = $model->getAccountsType();
        foreach($res as $v){
            if($v['code']==$info['account_type']){
                $info['name'] = $v['name'];
            }
        }

        $this->ajaxReturn(['code'=>200,'info'=>$info]);

    }
    /**
     * 申请提现 （提交）
     */
    public function withdrawal_sub(){
        $member_id = session('member_id');
        $id = I('post.id');
        $apply_money = I('post.apply_money');
        if(intval($apply_money)<100){
            $this->ajaxReturn(['code'=>300,'msg'=>'提现金额不能小于100']);
        }
        if(!is_int($apply_money/10)){
            $this->ajaxReturn(['code'=>300,'msg'=>'提现的金额不是10的倍数']);
        }
        $model = new TarentoBankAccountModel();

        $info = $model->where("member_id=$member_id and id=$id")->field("account_name,account_number,account_type")->find();
        if(empty($info)){
            $this->ajaxReturn(['code'=>300,'msg'=>'提现账户信息不存在']);
        }
        $info['apply_money'] = $apply_money;
        $info['apply_time'] = date('Y-m-d H:i:s',time());
        $model = new TarentoWithdrawApplyModel();
        $result = $model->add($info);
        if($result){
            $this->ajaxReturn(['code'=>200,'msg'=>'提现申请提交成功']);
        }else{
            $this->ajaxReturn(['code'=>200,'msg'=>'提现申请提交失败，请稍后再试']);

        }
    }

    /**
     * 收益明细
     */
    public function income_statement(){
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $num = ($page-1)*$limit;
        $type = I('post.type');  //0全部   1收入  2支出
        $member_id = session('member_id');
        $model = new TarentoModel();
        $t_info = $model->where("member_id=$member_id")->field("account")->find();
        $model = new TarentoCashFlowModel();
        //总收入
        $total_price = $model->where("member_id=$member_id and price>=0")->field("sum(price) as price")->find();
        //总支付
        $total_expenditure = $model->where("member_id=$member_id and price<0")->field("sum(price) as price")->find();
        if(empty($type)){
            $list = $model->where("member_id=$member_id")->limit($num,$limit)->order("create_time desc")->select();
        }else if($type==1){
            $list = $model->where("member_id=$member_id and price>=0")->limit($num,$limit)->order("create_time desc")->select();
        }else if($type==2){
            $list = $model->where("member_id=$member_id and price<0")->limit($num,$limit)->order("create_time desc")->select();
        }
        $this->ajaxReturn(['code'=>200,'total_price'=>$total_price['price'],'total_expenditure'=>$total_expenditure['price'],'list'=>$list,'total_account'=>$t_info['account']]);
    }

    /**
     * 销售总额 订单列表
     */
    public function total_sale_order_list(){
        $member_id = session('member_id');
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $num = ($page-1)*$limit;
        $model = new MicroShopBonusDetailModel();
        $res = $model->getEarnOrderIds1($member_id,$num,$limit);
        if (!empty($res['watitingEarnOrderIds'])) {
            //获取订单信息
            $orderIdWithBonusId = array_flip($res['watitingEarnOrderIds']);
            $orderModel = new OrderModel();
            $orders = $orderModel->getWaitingEarnOrdersByOrderIds($res['watitingEarnOrderIds']);

            foreach ($orders as $k => $v) {
                //获取订单支付金额
                $Helper = new Helper();
                $orders[$k]['pay_price'] = $Helper->getPayPrice($v)<0?0:$Helper->getPayPrice($v);
                //获取与当前店铺红包信息
                $model = new MicroShopBonusDetailModel();
                $orders[$k]['bonusInfo'] = $model->getInfoById($orderIdWithBonusId[$v['order_id']]);
            }
        }
        $this->ajaxReturn(['code'=>200,'list'=>$orders]);
    }

    /**
     * 粉丝列表
     */
    public function fens_list(){
        $member_id = session('member_id');
        //获取粉丝人数
        $model = new TarentoModel();
        $fens_num_c = $model->where("direct_rec_mid=$member_id and level=3")->count(); //吃货个数
        $fens_num_h = $model->where("direct_rec_mid=$member_id and level=2")->count(); //红人个数
        $fens_num_sx = $model->where("direct_rec_mid=$member_id and level=1")->count(); //红人个数
        $this->ajaxReturn(['code'=>200,'fens_num_c'=>$fens_num_c,'fens_num_h'=>$fens_num_h,'fens_num_sx'=>$fens_num_sx]);
    }

    /**
     * 获取推荐平级店铺列表
     * @param integer $memberId
     * @param integer $currentPage
     * @param integer $pageSize
     * @param integer $isNeedTotal
     */
    public function getRecEqualLevelList()
    {
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $level = I('post.level')?I('post.level'):3;
        $num = ($page-1)*$limit;
        $memberId = session('member_id');
        $model = new MicroShopModel();
        $shopInfo = $model->getInfoById($memberId);
        $model = new TarentoModel();
        $res = $model->getRecEqualLevelList($memberId,$level,$num,$limit);

        if (!empty($res['shopList'])) {
            $listShopsId = [];
            foreach ($res['shopList'] as $k => $v) {
                $listShopsId[] = $v['member_id'];
                //获取订单数
                $model = new OrderModel();
                $res['shopList'][$k]['orderCount'] = $model->getPaidNumByWithDateWithShops($v['member_id']);
                //获取红包收入
                $model = new MicroShopBonusGetRecordsModel();
                $res['shopList'][$k]['bonusAmount'] = $model->getAmount($v['member_id']);

                //获取团队销售额
                $model = new MicroShopSalesFlowModel();
                $saleAmounts1 = $model->getGroupAmount($v['member_id']);
                //获取当前用户下属于自己的那部分销售额
                $saleAmounts2 = $model->getSelfAmount($v['member_id']);

                $res['shopList'][$k]['saleAmounts'] = $saleAmounts1 + $saleAmounts2;
            }
            //获取店铺信息
            $model = new MicroShopModel();
            $shopsInfo = $model->getInfoByIds($listShopsId);
            $shopsInfoMap = [];
            foreach ($shopsInfo as $shop) {
                $shopsInfoMap[$shop['member_id']] = $shop;
            }
            //获取店主名称
            $model = new MemberModel();
            $members = $model->getInfoByIds($listShopsId);
            $shopMembers = [];
            foreach ($members as $member) {
                $shopMembers[$member['memberId']]= ['name' => $member['name']];
            }
            //合并
            $loop = $res['shopList'];
            foreach ($loop as $k => $v) {
                $res['shopList'][$k] = array_merge($v, $shopsInfoMap[$v['member_id']]);
                $res['shopList'][$k]['shopOwnerName'] = $shopMembers[$v['member_id']]['name'];
            }
            //查询对应每个店铺下面直接推荐首席、红人、吃货数量
            foreach($res['shopList'] as $k =>$vos){
                $model = new TarentoModel();
                $res['shopList'][$k]['childShopCount11'] = $model->countCustomerNumbers($vos['member_id'],1);
                $res['shopList'][$k]['childShopCount12'] = $model->countCustomerNumbers($vos['member_id'],2);
                $res['shopList'][$k]['childShopCount13'] = $model->countCustomerNumbers($vos['member_id'],3);
            }

           // var_dump($res);

        }
        $this->ajaxReturn(['code'=>200,'res'=>$res]);
    }

    /**
     * 店铺总订单列表
     */
    public function shop_order_list(){
        $member_id = session('member_id');
        $page = I('post.page')?I('post.page'):1;
        $limit = I('post.limit')?I('post.limit'):20;
        $num = ($page-1)*$limit;
        $orderModel = new OrderModel();
        $order_list = $orderModel->where("ms_id=$member_id and master_order_id='' and status !=-9")->order("create_time desc")->field("id,order_id,create_time,status,cost,cash_price,total_ms_taxation,ms_freight_risk,freight,cpns_price,member_id")->limit($num,$limit)->select();
        $model = new OrderProductModel();
        $m_model = new MemberModel();
        foreach($order_list as $k=>$v){
            $info = $m_model->where("userid=".$v['member_id'])->field("logo,name")->find();
            $total_price = 0;
            $order_list[$k]['member_log'] = $info['logo'];
            $order_list[$k]['member_name'] = $info['name'];
            //$total_price += floatval($v['cost']);//-floatval($v['cpns_price'])+floatval($v['freight'])+floatval($v['ms_freight_risk'])+floatval($v['total_ms_taxation']);
            $order_list[$k]['total_price'] = $v['cost'];
            $product_list = $model->alias('op')->join("left join haiou_stock_shops as s on s.id=op.stock_shop")->where("op.order_id='".$v['order_id']."'")->field('op.*,s.title as stock_shop_title')->select();
            $order_list[$k]['product_list'] = $product_list;
        }
       $this->ajaxReturn(['code'=>200,'order_list'=>$order_list]);
    }

}